package com.situ.parking;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.situ.JDBC.JDBCUtil;

public class RecordDao {

	/**
	 * 执行insert-sql插入一条记录
	 * 
	 * @param model
	 * @return
	 * @throws SQLException
	 */
	public int insert(RecordModel model) {
		String sql = "insert into p_record(number,plate,type,fee,time)values(?,?,?,?,?)";
		Connection conn = JDBCUtil.getConnection();
		PreparedStatement ps = null;
		if (conn == null)
			return 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setInt(1, model.getNumber());
			ps.setString(2, model.getPlate());
			ps.setInt(3, model.getType());
			ps.setInt(4, model.getFee());
			ps.setInt(5, model.getTime());
			return ps.executeUpdate(); // 执行sql语句，并返回影响的行数
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 根据多个查询条件 - 执行查询sql，返回结果构成的实体类集合
	 * 
	 */
	public List<RecordModel> selectList() {
		// 要进行字符串拼接，使用StringBuffer/StringBuilder
		StringBuffer sql = new StringBuffer("select number,plate,type,fee,time from p_record ");
		Connection conn = JDBCUtil.getConnection();
		if (conn == null)
			return null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<RecordModel> list = new ArrayList<>();
		try {
			ps = conn.prepareStatement(sql.toString());
			rs = ps.executeQuery();
			RecordModel r = null;
			while (rs.next()) {// ORM（把数据库的表的信息转换成数据库的过程）
				r = new RecordModel();
				r.setNumber(rs.getInt("number"));
				r.setPlate(rs.getString("plate"));
				r.setType(rs.getInt("type"));
				r.setFee(rs.getInt("fee"));
				r.setTime(rs.getInt("time"));
				list.add(r);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(conn, ps, rs);
		}
		return list;
	}


}
